package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.Util.CopyUtil;
import com.jiawa.wiki.Util.SnowFlake;
import com.jiawa.wiki.domain.Doc;
import com.jiawa.wiki.domain.DocExample;
import com.jiawa.wiki.mapper.DocMapper;
import com.jiawa.wiki.req.DocQueryReq;
import com.jiawa.wiki.req.DocSaveReq;
import com.jiawa.wiki.resp.DocQueryResp;
import com.jiawa.wiki.resp.PageResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {
    @Resource
    public DocMapper docMapper;

    @Resource
    public SnowFlake snowFlake;
    private final static Logger LOG = LoggerFactory.getLogger(DocService.class);

    public PageResp<DocQueryResp> getlist(DocQueryReq req){
        DocExample docExample = new DocExample();

        DocExample.Criteria criteria = docExample.createCriteria();

        PageHelper.startPage(req.getPage(), req.getSize());

        List<Doc> docList = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);

        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getTotal());

        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    public List<DocQueryResp> all(){
        DocExample docExample = new DocExample();

        docExample.setOrderByClause("sort asc");

        List<Doc> docList = docMapper.selectByExample(docExample);

        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;
    }


    public void save(DocSaveReq req){

        Doc doc = CopyUtil.copy(req,Doc.class);

        if (!ObjectUtils.isEmpty(req.getId())) {
            //更新功能
            docMapper.updateByPrimaryKey(doc);
        }else {
            //新增
            doc.setId(snowFlake.nextId());

            docMapper.insert(doc);
        }

    }

    //删除
    public void delete(long id){
        docMapper.deleteByPrimaryKey(id);

    }




}